var express = require("express");
var router = express.Router();
var User = require("../../models/webSite/user");
var md5 = require("md5");
var isLogin = require("./public/is-login.js");
//node加密模块(自带)
var crypto = require("crypto");
//判断是否登录
router.get("/register" , isLogin.checkNotLogin);
router.get("/register" , function(req , res){
	res.render("webSite/register" , {
		title : "欢迎来到注册页"
	});
});
//post
//判断是否登录
router.post("/register" , isLogin.checkNotLogin);
router.post("/register" , function(req , res){
		userInfo = req.body,
		password = md5(userInfo.password),
		data = {
			name : userInfo.name,
			email : userInfo.email,
			password : password
		},
		user = new User(data);
	if(!userInfo.name){
		return res.json({
			state : "error",
			message : "用户名不能为空"
		});
	};
	if(!userInfo.email){
		return res.json({
			state : "error",
			message : "邮箱不能为空"
		});
	};
	if(!userInfo.password){
		return res.json({
			state : "error",
			message : "密码不能为空"
		});
	};
	user.getUser(data.name , function(err , data){
		if(err){
			console.log("错误");
			return res.json({
				state : "error",
				message : errr
			});
		};
		if(data){
			return res.json({
				state : "error",
				message : "用户已存在!"
			});
		};
		//如果用户不存在也没出错就执行保存
		holdUser();
	});
	//保存
	function holdUser(){
		user.create(function(data){
			req.session.user = data;
			//返回成功
			res.json({
				state : "ok",
				message : "",
				data : data
			});
		});
	};
});
//接口
module.exports = router;
